package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.CodeUtil;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    SmsService smsService;
    @Autowired
    UserInfoMapper userInfoMapper;


    /**
     * 获取短信验证码
     * @param phone
     */
    @Override
    public void getCode(String phone) {
        //把这个验证码写入Redis中,并设置k-v键值对的有效期为一分钟
        String redisKey = RedisConstant.APP_LOGIN_PREFIX + phone;
        //把短信发送给用户之前看看用户在一分钟之内有没有发送过短信,短信发送不能过于频繁
        Boolean haveKey = redisTemplate.hasKey(redisKey);
        if (haveKey){
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }else {
            //获取到一个随机的短信验证码
            String code = CodeUtil.getCode(6);
            //最后把该短信发给用户手机
            smsService.sendCode(phone,code);
            redisTemplate.opsForValue().set(redisKey,code,RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC, TimeUnit.SECONDS);
        }
    }

    /**
     * 登录和注册
     * @param loginVo
     * @return
     */
    @Override
    public String login(LoginVo loginVo) {
        //判断手机号码是否为空
        if (loginVo.getPhone() == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //判断验证码是否为空
        if (loginVo.getCode() == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //组建key
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        //判断验证码是否不在(如果不在就说明验证码过期了)
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //验证码错误
        String code = (String) redisTemplate.opsForValue().get(key);
        if (!code.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        //从数据库中查询出信息看是否为空
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo user = userInfoMapper.selectOne(queryWrapper);
        String jwt;
        if (user == null){
            // 说明是新用户  ,需要完成注册
            UserInfo userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户-" + loginVo.getPhone().substring(7));
            userInfoMapper.insert(userInfo);
            //插入到数据库后生成jwt令牌
            jwt = JwtUtil.createJWT(userInfo.getId(),userInfo.getPhone());

        }else {
            // 说明已经注册了,看看账号是否被禁用了
            if (user.getStatus().equals(BaseStatus.DISABLE)){
                throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
            }
            //登录成功,生成jwt令牌
            jwt = JwtUtil.createJWT(user.getId(), user.getPhone());

        }
        return jwt;

    }

    /**
     * 获取移动吨用户信息
     * @param userId
     * @return
     */
    @Override
    public UserInfoVo getLoginUserById(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());
        return userInfoVo;
    }
}
